Ext.onReady(function() {
	var loadMask = new Ext.LoadMask(Ext.getBody(), {msg:"请稍后, 后台正在处理..."});
	var toolbar = Ext.create('Ext.toolbar.Toolbar', {
		dock : 'top',
		items : [{
					text : '返回',
					xtype : 'button',
					listeners : {
						click : function() {
							location.href = "/wuziMgr/wz_ly";
						}
					}
				}, {
					text : '添加',
					xtype : 'button',
					listeners : {
						click : function() {
							var grid = Ext.getCmp("orders");
							var store = grid.getStore();
							var models = store.getRange(0, store.getCount());
							var Orders = [];
							for(var i=0; i<models.length;i++){
								Ext.Array.include(Orders, {
									DeviceId : models[i].get("DeviceId"),
									Count : models[i].get("Count")
								});
							}
							var jsonData = {
								DepartmentId : Ext.getCmp("Department").getValue(),
								GroupId: Ext.getCmp("Flight").getValue(),
								UserId: Ext.getCmp("User").getValue(),
								Time: Ext.Date.format(Ext.getCmp("Time").getValue(),"Y-m-d H:i:s"),
								Desp: Ext.getCmp("Desp").getValue(),
								Orders: Orders
							}
							Ext.Ajax.request({
								url : "/device_recipient/add",
								type : "POST",
								jsonData: jsonData,
								callback : function(options, success, response) {
									if (success) {
										var result = Ext
												.decode(response.responseText);
										if (result.success) {
											location.href = "/wuziMgr/wz_ly";
										} else {
											Ext.Msg.alert("错误", result.msg);

										}
									}
								}
							})
						}
					}
				}]
	});
	var departmentStore = Ext.create('Ext.data.Store', {
				fields : [{
							name : 'Id',
							type : 'int'
						}, 'Name'],
				proxy : {
					type : 'ajax',
					url : '/department/all',
					reader : {
						type : 'json',
						root : 'data.rows'
					}
				},
				autoLoad : true
			});

	var department = Ext.create('Ext.form.ComboBox', {
				fieldLabel : '部门',
				labelWidth : 60,
				width : 200,
				editable : false,
				id : 'Department',
				store : departmentStore,
				queryMode : 'local',
				displayField : 'Name',
				valueField : 'Id'
			});

	var flightStore = Ext.create('Ext.data.Store', {
				fields : ["Id", 'Name'],
				proxy : {
					type : 'ajax',
					url : '/flight/all',
					reader : {
						type : 'json',
						root : 'data.rows'
					}
				},
				autoLoad : true
			});

	var flight = Ext.create('Ext.form.ComboBox', {
				fieldLabel : '班组',
				labelWidth : 60,
				width : 200,
				id : 'Flight',
				store : flightStore,
				editable : false,
				queryMode : 'local',
				displayField : 'Name',
				valueField : 'Id',
				listeners: {
					change: function(self, newValue, oldValue){
						var dptId = department.getValue();
						userStore.proxy.url = '/user/find_by_dept_flight/' + dptId + '/' + newValue;
						userStore.reload();
					}
				}
			});
	var userStore = Ext.create('Ext.data.Store', {
				fields : ["Id", "Username", 'Name'],
				proxy : {
					type : 'ajax',
					url : '/user/all',
					reader : {
						type : 'json',
						root : 'data.rows'
					}
				},
				autoLoad : true
			});
	var recipientor = Ext.create("Ext.form.ComboBox",{
		fieldLabel : '领用人',
		labelWidth : 60,
		width : 200,
		editable : false,
		id : 'User',
		store : userStore,
		queryMode : 'local',
		valueField : 'Id',
		tpl: Ext.create('Ext.XTemplate',
        '<tpl for=".">',
            '<div class="x-boundlist-item">{Username}({Name})</div>',
        '</tpl>'
	    ),
	    displayTpl: Ext.create('Ext.XTemplate',
	        '<tpl for=".">',
	            '{Username}({Name})',
	        '</tpl>'
	    )
	});
			
	var deviceStore = Ext.create('Ext.data.Store', {
				fields : ['Id', {
							name : "Type",
							type : "object"
						}, "Model"],
				proxy : {
					type : 'ajax',
					url : '/device/distinct',
					reader : {
						type : 'json',
						root : 'data.rows'
					}
				},
				autoLoad : true
			});

	var device = Ext.create('Ext.form.ComboBox', {
				id : "device",
				labelWidth : 60,
				width : 200,
				fieldLabel : '设备类型',
				store : deviceStore,
				allowBlank: false,
				editable : false,
				queryMode : 'local',
				valueField : 'Id',
				tpl : Ext
						.create(
								'Ext.XTemplate',
								'<tpl for=".">',
								'<div class="x-boundlist-item">{Type.Name}({Model})</div>',
								'</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">',
						'{Type.Name}({Model})', '</tpl>'),
				listeners:{
					change: function(self, newValue, oldValue){
						loadMask.show();
						Ext.Ajax.request({
							url: '/device/available',
							params:{
								id: newValue
							},
							callback: function(options, success, response){
								loadMask.hide();
								if(success){
									var ar = Ext.decode(response.responseText);
									if(ar.success){
										Ext.getCmp("Count").setMaxValue(ar.data);
									}
								}
							}
						})
					}
				}
			});
	var addPanel1 = Ext.create('Ext.toolbar.Toolbar', {
				dock : 'top',
				border : false,
				items : [department, flight,recipientor]
			});
	var addPanel2 = Ext.create('Ext.form.Panel', {
				dock : 'top',
				layout: 'hbox',
				margin: '0 10',
				border : false,
				items : [device, {
							xtype : 'numberfield',
							id : "Count",
							labelWidth : 60,
							allowBlank: false,
							margin: '0 5',
							width : 200,
							maxValue:1,
							minValue: 1,
							fieldLabel : '数量'
						}, {
							xtype : "button",
							margin: '0 5',
							text : "加入",
							listeners : {
								click : function() {
									if(!addPanel2.isValid()){
										return;
									}
									var store = device.getStore();
									var deviceId = device.getValue()
									var record = store.findRecord("Id",
											deviceId);
									var grid = Ext.getCmp("orders");
									var gridStore = grid.getStore();

									var tmp = gridStore.findRecord("DeviceId",
											deviceId);
									if (tmp != null) {
										var countCmp = Ext.getCmp("Count");
										var addCount = countCmp.getValue();
										var count = tmp.get('Count'); 
										if(( count + addCount) > countCmp.maxValue){
											Ext.Msg.alert('错误', '该设备最多可以添加' + countCmp.maxValue + '个');
											return;
										}
										tmp.set("Count", count + addCount);
										gridStore.commitChanges();
									} else {
										gridStore.add({
													DeviceId : deviceId,
													Name : record.get("Type").Name,
													Model : record.get("Model"),
													Count : Ext.getCmp("Count")
															.getValue()
												});
									}
								}
							}
						}]
			});

	var store = Ext.create('Ext.data.Store', {
				fields : ["DeviceId", "Name", "Model", {name:"Count",type:'int'}]
			});
	var grid = Ext.create('Ext.grid.Panel', {
				id : "orders",
				minHeight : 100,
				selType : 'checkboxmodel',
				store : store,
				margin : '5 10',
				columns : [{text : '序号',
							xtype : 'rownumberer',
							width : 40,
							sortable : false
						}, {
							text : '设备类型',
							flex: 1,
							renderer: function(v, meta, record){
								return record.get('Name') + '(' + record.get('Model') + ')';
							}
						}, {
							text : '数量',
							dataIndex : 'Count'
						}, {
							text : '操作',
							xtype : 'actioncolumn',
							width : 50,
							items : [{
										icon : 'view/images/delete.png',
										tooltip : 'Delete',
										handler : function(grid, rowIndex,
												colIndex) {
											grid.getStore().removeAt(rowIndex);
										}
									}]
						}]
			});

	var panel = Ext.create("Ext.panel.Panel", {
				title : '',
				autoScroll:true,
				border : false,
				bodyBorder : false,
				dockedItems : [toolbar, addPanel1, addPanel2],
				items : [grid, {
							xtype : 'label',
							text : '用途说明',
							margin : "0 0 0 10"
						}, {
							xtype : 'textareafield',
							id: "Desp",
							width: '90%',
							margin: '5 10',
							grow : true
						},{
							xtype: 'datefield',
							id: "Time",
							labelWidth:60,
							width:250,
							margin: '5 10',
					        fieldLabel: '领用时间',
					        format: 'Y-m-d H:i:s',
					        value: new Date()
						}]
			});
	Ext.create('Ext.Viewport', {
				layout : 'fit',
				style : 'background:none;background-color:white;',
				items : [panel]
			});
});